package util;

import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Yangzhenyu06
 * @date 2021/8/22 11:11 下午
 */
public class StringTemplateFormatUtils {

    private static final String DEFAULT_REGEX = "\\{(.+?)\\}";
    private static final Pattern DEFAULT_PATTERN = Pattern.compile(DEFAULT_REGEX);

    public static String render(String template, Map<String, String> params) {
        return doRender(template, params, DEFAULT_PATTERN);
    }

    public static String render(String template, Map<String, String> params,String regex) {
        if(StringUtils.isBlank(regex)){
            return template;
        }
        Pattern pattern = Pattern.compile(regex);
        return doRender(template, params, pattern);
    }

    private static String doRender(String template, Map<String, String> params, Pattern pattern){
        if(StringUtils.isBlank(template)){
            return "";
        }
        if(params==null || params.size()==0){
            return template;
        }
        try {
            StringBuffer sb = new StringBuffer();
            Matcher matcher = pattern.matcher(template);
            while (matcher.find()) {
                String name = matcher.group(1);// 键名
                String value = params.get(name);// 键值
                value = value==null ? "" : value;
                matcher.appendReplacement(sb, value);
            }
            matcher.appendTail(sb);
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return template;
    }
}
